//
//  SSPictureView.swift
//  weibo
//
//  Created by 邵帅 on 16/6/28.
//  Copyright © 2016年 groupNineObject. All rights reserved.
//

import UIKit
import SDWebImage

///  视图和cell的间距
let SSPictrueViewMargin: CGFloat = 10
/// item间距
let SSPictureItemMargin: CGFloat = 5
/// item的宽和高
let  SSPictureItemWH   = (UIScreen.mainScreen().bounds.width - 2 * SSPictrueViewMargin - 2 * SSPictureItemMargin) / 3

let SSPictureViewReuseIdentifier = "SSPictureViewReuseIdentifier"

class SSPictureView: UICollectionView {
    
    var pic_urls: [SSPhotoViewModel]? {
        
        didSet{
            
            let size = calcSize()
            
            self.snp_updateConstraints { (make) in
                
                make.width.equalTo(size.width)
                make.height.equalTo(size.height)
            }
            
            reloadData()
        }
     
    }
    
    var flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        dataSource = self
        delegate = self
        
        self.registerClass(SSPictureCollectionViewCell.self, forCellWithReuseIdentifier: SSPictureViewReuseIdentifier)
        
        // 设置itemsize
        flowLayout.itemSize = CGSizeMake(SSPictureItemWH, SSPictureItemWH)
        flowLayout.minimumInteritemSpacing = SSPictureItemMargin
        flowLayout.minimumLineSpacing = SSPictureItemMargin
        
    }
    

    private func calcSize() ->CGSize {
        
        guard let count = pic_urls?.count else {
            return CGSizeZero
        }
        
        if count == 1 {
            
            let key = pic_urls?.first?.model?.thumbnail_pic
            
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        
            if image == nil {
                
                flowLayout.itemSize = CGSizeMake(SSPictureItemWH, SSPictureItemWH)
                return CGSizeMake(SSPictureItemWH, SSPictureItemWH)
            }
            
            var size = image.size
            
            // 过窄的处理
            if size.width < 80 {
                
                let width: CGFloat = 80
                let height = width / size.width * size.height
                
                size.width = width
                // 约束最大的高度
                size.height = height > 150 ? 150 : height
            }else if size.width > 200 {
                // 图片过宽的处理
                let width: CGFloat = 200
                let height = width / size.width * size.height
                
                size.width = width
                size.height = height
            }
            
            flowLayout.itemSize = size
            
            return size
        }else {
            
            flowLayout.itemSize = CGSizeMake(SSPictureItemWH, SSPictureItemWH)
        }
        
        if count == 4 {
            
            return CGSizeMake(SSPictureItemWH * 2 + SSPictureItemMargin, SSPictureItemWH * 2 + SSPictureItemMargin)
        }
        
        let row = (count - 1) / 3 + 1
        
        return CGSizeMake(UIScreen.mainScreen().bounds.width - 2*SSPictrueViewMargin,(SSPictureItemMargin +  SSPictureItemWH)*CGFloat(row))
    }
    
    
}


extension SSPictureView: UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return pic_urls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(SSPictureViewReuseIdentifier, forIndexPath: indexPath) as!SSPictureCollectionViewCell
        
        cell.viewModel = pic_urls![indexPath.item]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let userInfo = ["pic_urls": pic_urls!,"indexPath": indexPath]
        
        NSNotificationCenter.defaultCenter().postNotificationName(kNotificationBigPicture, object: nil, userInfo: userInfo)
    }
    
}

class SSPictureCollectionViewCell: UICollectionViewCell{
    
    var viewModel: SSPhotoViewModel?{
        
        didSet{
            
            iconImageView.sd_setImageWithURL(viewModel?.imageURL)
        }
    }
    
    // 第一步 -- 重写构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 第二步 -- 定义一个方法,来实现 视图的添加和布局
    private func setupUI(){
        
        contentView.addSubview(iconImageView)
        
        // 设置约束
        iconImageView.snp_makeConstraints { (make) -> Void in
            
            //            make.edges.equalTo(contentView.snp_edges)
            make.left.equalTo(contentView.snp_left)
            make.top.equalTo(contentView.snp_top)
            make.width.equalTo(contentView.snp_width)
            make.height.equalTo(contentView.snp_height)
            
        }
        
    }
    
    // 第三步: 懒加载控件
    private lazy var iconImageView: UIImageView = {
        
        let img = UIImageView()
        
        // 图片的填充模式
        img.contentMode = .ScaleToFill
        
        
        return img
    }()
    
    
}


